﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace LoadGenerator
{
    class LoadGenerator
    {
        static void Main(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("Usage: LoadGenerator <patternfile> <port> <host> <user type: one of " + UserTypeRegistry.instance.registeredTypes() + ">");
                return;
            }

            LoadConfiguration load = new LoadConfiguration(args[0]);
            SvrConf conf = new SvrConf();
            conf.port = int.Parse(args[1]); 
            conf.hostname = args[2];
            String whichtest = args[3];
            if (!UserTypeRegistry.instance.registeredType(whichtest))
            {
                Console.WriteLine("Type has to be one of: " + UserTypeRegistry.instance.registeredTypes());
                return;
            }

            bool done = false;
            while (!done)
            {
                int users = load.load;
                if (users <= 0)
                    done = true;
                else
                {
                    object waittostart = new object();
                    User[] curr = new User[users];
                    Thread[] threads = new Thread[users];
                    for (int i = 0; i < users; i++)
                    {
                        curr[i] = UserTypeRegistry.instance.create(whichtest, conf, waittostart, i);
                        threads[i] = new Thread(curr[i].runUser);
                        threads[i].Start();
                    }

                    Thread.Sleep(1000);

                    lock (waittostart)
                    {
                        Monitor.PulseAll(waittostart); //let all threads start at one go.
                    }

                    for (int i = 0; i < users; i++)
                        threads[i].Join(); //wait till finish
                    done = false; //post only once.
                }
                Thread.Sleep(1000); //load every 1s.
            }
        }
    }
}
